import Vue from 'vue';
import Router from 'vue-router';
import { getNav } from '@/api/menu';
import { getToken } from '@/utils/auth'; // 验权
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css'; // Progress 进度条样式
import {
  setToken
} from '@/utils/auth';

Vue.use(Router);

const component = {
  'app': () => import('@/App'),
  'layout': () => import('@/views/layout/Layout'),
  'empty': () => import('@/views/layout/empty'),
  'dashboard': () => import('@/views/dashboard/index'),
  'table': () => import('@/views/table/index'),
  'tree': () => import('@/views/system/menu'),
  'form': () => import('@/views/form/index'),
  'menu': () => import('@/views/system/menu'),
  'role': () => import('@/views/system/role'),
  'user': () => import('@/views/system/user'),
  'sysPassword': () => import('@/views/password/sysPassword'),
  'userPassword': () => import('@/views/password/userPassword'),
  'assign': () => import('@/views/password/assign'),
  'statisticsApp': () => import('@/views/statistics/app'),
  'statisticsDashboard': () => import('@/views/statistics/dashboard'),
  'statisticsRequestTime': () => import('@/views/statistics/requestTime'),
  'statisticsErrorLogList': () => import('@/views/statistics/errorLogList'),
  'IPQuery': () => import('@/views/statistics/IP-query'), // IP查询

  'abnormalBehavior': () => import('@/views/member-exception-filtering/abnormal-behavior/index'), // 异常行为筛选
  'defaultRules': () => import('@/views/member-exception-filtering/default-rules/index'), // 默认规则筛选名单
  'exceptionUserManagement': () => import('@/views/member-exception-filtering/exception-member-management/index'), // 用户异常管理
  'whiteList': () => import('@/views/member-exception-filtering/white-list/index'), // 白名单用户管理
  'memberQuery': () => import('@/views/member-exception-filtering/member-query/index'), // 会员查询
  'cancellationApply': () => import('@/views/member-exception-filtering/cancellation-apply/index'), // 会员查询

  'capitalFlowMonitoring': () => import('@/views/activity-anomaly-analysis/capital-flow-monitoring/index'), // 资金流量监控
  'flowMonitoring': () => import('@/views/activity-anomaly-analysis/flow-monitoring/index'), // 流量监控
  'userDetail': () => import('@/views/user-details/index'), // 用户详情

  'integralFun': () => import('@/views/analysis-function/integral/index'), // 积分系统
  'operationLog': () => import('@/views/operation-log/index'), // 操作日志

  'warning': () => import('@/views/forewarningManagement/warning.vue'), // 预警管理
  'warningDetail': () => import('@/views/forewarningManagement/warningDetail.vue'), // 预警管理详情

  'ActiveUser': () => import('@/views/user-analysis/ActiveUser.vue'), // 活跃用户
  'NewUser': () => import('@/views/user-analysis/NewUser.vue'), // 新增用户
  'RecentActiveUser': () => import('@/views/user-analysis/RecentActiveUser.vue'), // 最近活跃用户
  'UsageTime': () => import('@/views/user-analysis/user-engagement/UsageTime.vue'), // App使用时长
  'UsageFrequency': () => import('@/views/user-analysis/user-engagement/UsageFrequency.vue'), // App使用频率
  'InformationRead': () => import('@/views/user-analysis/user-engagement/InformationRead.vue'), // 用户资讯阅读
  'AppFunctionAnalysis': () => import('@/views/analysis-function/app-function/AppFunctionAnalysis.vue'), // app功能分析
  'NewsClickCount': () => import('@/views/user-analysis/NewsClickCount.vue'), // 资讯点击量统计

  'DataOverView': () => import('@/views/data-overview'), // 数据概览
  'UserRetention': () => import('@/views/user-analysis/user-retention'), // 用户留存
  'SysAnalysis': () => import('@/views/user-analysis/sys-analysis'), // 系统分析
  'InfoCountAnalysis': () => import('@/views/information-content-analysis/info-count-analysis'), // 资讯量分析
  'InfoReadingAnalysis': () => import('@/views/information-content-analysis/Info-reading-analysis'), // 资讯阅读分析
  'InfoChannelAnalysis': () => import('@/views/information-content-analysis/info-channel-analysis'), // 资讯频道分析
  'InfoCententAnalysis': () => import('@/views/information-content-analysis/infoContentAnalysis'), // 资讯频道分析
  'ContentListData': () => import('@/views/information-content-analysis/ContentListData'), // 资讯列表数据
  'ContentDetail': () => import('@/views/information-content-analysis/ContentDetail'), // 资讯详情页

  'UserPortrait': () => import('@/views/recommended-analysis/UserPortrait.vue'), // 用户画像
  WemediaPortrait: () => import('@/views/recommended-analysis/WemediaPortrait.vue'), // 用户画像
  'NewsFunnelAnalysis': () => import('@/views/recommended-analysis/NewsFunnelAnalysis.vue'), // 资讯漏斗分析
  'RecommendEffect': () => import('@/views/recommended-analysis/RecommendEffect.vue'), // 推荐效果

  'VlogClickRate': () => import('@/views/recommended-analysis/VlogClickRate.vue'), // 推荐效果 小视频点击率
  'NewsFeedClickRate': () => import('@/views/recommended-analysis/NewsFeedClickRate.vue'), // 推荐效果 微头条推荐
  'PerCapitaReadingTime': () => import('@/views/recommended-analysis/PerCapitaReadingTime.vue'), // 推荐效果  人均阅读时长

  'activityPushAnalyze': () => import('@/views/activity-analysis/push-analyze/index'), // 活动分析-push分析
  'advertisementClick': () => import('@/views/advertisement/advertisementClick'), // 广告点击统计
  'internalAdvertisingRecords': () => import('@/views/advertisement/InternalAdvertisingRecords'), // 内部广告记录
  'advertisingDetails': () => import('@/views/advertisement/AdvertisingDetails'), // 广告明细

  'collapseRate': () => import('@/views/online-quality/CollapseRate.vue'), // App崩溃率
  'interface': () => import('@/views/online-quality/Interface.vue'), // 接口响应
  'dailyoperationanalysis': () => import('@/views/weMedia-revenue-analysis/DailyOperationAnalysis.vue'), // 自媒体收益分析 日度运营分析
  'monthlyoperationanalysis': () => import('@/views/weMedia-revenue-analysis/MonthlyOperationAnalysis.vue'), // 自媒体收益分析 日度运营分析
  'ThematicDataOverview': () => import('@/views/thematic-section-analysis/thematic-data-overview'), // 专题数据总览
  'singleTopicAnalysis': () => import('@/views/thematic-section-analysis/single-topic-analysis'), // 单一专题分析
  'singleThematicStatement': () => import('@/views/thematic-section-analysis/single-thematic-statement'), // 单一专题报表
  'thematicContentAnalysis': () => import('@/views/thematic-section-analysis/thematic-content-analysis'), // 专题内容分析
  'thematicReport': () => import('@/views/thematic-section-analysis/thematic-report'), // 专题内容报表
  'RechargeReconciliation': () => import('@/views/recharge-reconciliation/Recharge-reconciliation'), // 充值对账
  'WithdrawalReview': () => import('@/views/realization-audit/WithdrawalReview'), // 提现审核
  'AwardOfBonuses': () => import('@/views/realization-audit/AwardOfBonuses'), // 批量发放奖金
  'releaseprocessing': () => import('@/views/member-exception-filtering/ReleaseProcessing') // 异常解除申请处理
};
/**
 *全局路由，不显示到菜单中的
 **/
export const globalRoutes = [{
  path: '/login',
  component: () =>
    import('@/views/login/index')
},
{
  path: '/404',
  component: () =>
    import('@/views/404')
}
];

/**
 * 主路由
 * 显示到菜单中的
 * @type {Array}
 */
export const mainRoutes = {
  path: '/',
  component: component['layout'],
  name: 'userMenus',
  children: [
    {
      path: '/',
      name: 'Dashboard',
      meta: { title: '首页', icon: 'form' },
      component: component['dashboard']
    },
    {
      path: 'userExceptionFilter',
      meta: { title: '会员详情', icon: 'user' },
      hidden: true,
      component: component['empty'],
      children: [{
        path: 'userDetail',
        name: 'userDetail',
        meta: { title: '会员详情', icon: 'user' },
        hidden: true,
        component: component['userDetail']
      }]
    },
    {
      path: 'warningManagement',
      meta: { title: '预警管理', icon: 'user' },
      hidden: true,
      component: component['empty'],
      children: [{
        path: 'warningDetail',
        name: 'userDetail',
        meta: { title: '预警详情', icon: 'user' },
        hidden: true,
        component: component['warningDetail']
      }]
    },
    {
      path: 'userAnalysis',
      meta: { title: '用户分析', icon: 'user' },
      hidden: true,
      component: component['empty']
    },
    {
      path: 'Usersengagement',
      meta: { title: '用户参与度', icon: 'user' },
      hidden: true,
      component: component['empty']
    },
    {
      path: 'appFunctions',
      meta: { title: 'App功能', icon: 'user' },
      hidden: true,
      component: component['empty']
    },
    {
      path: 'internalAdvertisingRecords',
      meta: { title: '内部广告记录', icon: 'user' },
      hidden: true,
      component: component['empty'],
      children: [{
        path: 'advertisingDetails',
        name: 'advertisingDetails',
        meta: { title: 'ad_details', icon: 'user' },
        hidden: true,
        component: component['advertisingDetails']
      }]
    },
    {
      path: 'thematicSectionAnalysis',
      hidden: true,
      component: component['empty'],
      children: [{
        path: 'singleThematicStatement',
        name: 'singleThematicStatement',
        meta: { title: 'single_topic_statement', icon: 'chat' },
        hidden: true,
        component: component['singleThematicStatement']
      }, {
        path: 'thematicContentAnalysis',
        name: 'thematicContentAnalysis',
        meta: {
          title: ' 专题内容分析',
          icon: 'chat'
        },
        hidden: true,
        component: component['thematicContentAnalysis']
      }, {
        path: 'thematicReport',
        name: 'thematicReport',
        meta: {
          title: ' 专题内容报表',
          icon: 'chat'
        },
        hidden: true,
        component: component['thematicReport']
      }]
    },
    {
      path: 'ContentListData',
      meta: { title: '资讯内容分析', icon: 'user' },
      hidden: true,
      component: component['empty'],
      children: [{
        path: 'contentDetail',
        name: 'contentDetail',
        meta: { title: '内容数据详情', icon: 'user' },
        hidden: true,
        component: component['ContentDetail']
      }]
    }
  ]
};

const router = new Router({
  scrollBehavior: () => ({ y: 0 }),
  isAdd: false, // 是否已经添加动态路由
  routes: globalRoutes.concat(mainRoutes)
});

function isGlobalRoute(route) {
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return true;
    }
  }
  return false;
}

router.beforeEach((to, from, next) => {
  NProgress.start();
  const token = getToken();
  if (token) {
    if (router.options.isAdd || isGlobalRoute(to)) {
      next();
    } else {
      getNav().then(response => {
        // 存储风控是否有最高权限
        localStorage.setItem('full_rule_name', response.data.permission.indexOf('risk:full_rule_name') != -1);
        const main = menuToRoute(response.data.menuList);
        mainRoutes.children = mainRoutes.children.concat(main);
        router.addRoutes([
          mainRoutes,
          { path: '*', redirect: '/404' }
        ]);
        router.options.isAdd = true;
        next({ ...to, replace: true });
      });
    }
  } else {
    // 本地开发使用携带token进行跳转
    if (process.env.TARGET_ACTION == 'dev') {
      if (to.query.token) {
        setToken(to.query.token);
      } else {
        throw new Error(`开发环境请在URL地址的query中携带token字段进行跳转,

例如: http://localhost:9527/token=61efd2ef-74dc-47a8-8415-436544530bea
token 可以从对应环境的资讯管理后台获取，打开控制台 -> 切换到应用 -> 选中Cookies，找到对应环境的token键名，

例如：测试环境的键名为 test_tnaot_token
复制对应的值即可`);
      }
    } else {
      const path = encodeURIComponent(`${process.env.DATA_ADMIN}/#${to.path}`).replace('/', '%2F');
      window.location.href = `${process.env.SHARE_LOGIN_API}?url=${path}`; // 全部重定向到共享登录页
    }
  }
});
router.afterEach(() => {
  NProgress.done(); // 结束Progress
});

function menuToRoute(menuList = []) {
  const routes = [];
  for (const menu of menuList) {
    var path = menu.url;
    var componentName = menu.url || 'app';
    var link = null;
    if (componentName.indexOf('url@') > -1) {
      componentName = 'statisticsDashboard';
      var pathAndParam = path.replace('url@', '');
      path = encodeURIComponent(pathAndParam).replace('/', '%2F');
      link = pathAndParam;
    }
    const route = {
      path: path,
      component: component[componentName],
      name: menu.url,
      hidden: menu.hidden,
      meta: {
        link: link,
        title: menu.name,
        icon: menu.icon
      },
      children: null
    };
    if (menu.children && menu.children.length > 0) {
      route.component = component['empty'];
      route.children = menuToRoute(menu.children);
    }
    routes.push(route);
  }
  return routes;
}

export default router;
